//
//  InfoMapViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/4/25.
//

#import "InfoMapViewController.h"
#import "AddressBottomView.h"
@interface InfoMapViewController ()<MKMapViewDelegate,UITextFieldDelegate>
@property (nonatomic , strong) MKMapView * mapView;
@property (nonatomic , strong) UITextField * textField;
@property (nonatomic , strong) UILabel * addressLabel;
@property (nonatomic , strong) HeaderView * addButton;
@property (nonatomic , strong) CLPlacemark * seletedPlace;
@property (nonatomic , strong) SQCustomButton * dingwei;

@end

@implementation InfoMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   [[SQCLLocationManager sharedManager] SQ_startUpdatingLocation];
    
}

- (void)SQ_UIViewForSelfView{
    WS(weakSelf);
    [self.view addSubview:self.mapView];
    UIImageView * image = [[UIImageView alloc]init];
    image.image = SQGetImage(@"datouzhen");
    image.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.view);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(40);
    }];
    SQCustomButton * add = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
    add.image = SQGetImage(@"不喜欢");
    [self.view addSubview:add];
    [add mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(TopHeight-50);
        make.size.mas_equalTo(50);
        make.right.equalTo(self.view.mas_right).offset(-4);
    }];
    [add setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [self.view addSubview:self.addressLabel];
    [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(image.mas_top).offset(-4);
        make.width.mas_equalTo(SCREEN_WIDETH/2.f);
    }];
    if (self.isEdit) {
        add.hidden = YES;
        [self.zx_navBar addSubview:self.textField];
        [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.zx_navBar);
            make.width.mas_equalTo(SCREEN_WIDETH-120);
            make.height.mas_equalTo(40);
            make.centerY.equalTo(self.zx_navLeftBtn);
        }];
    } else{
        [self.view addSubview:self.textField];
        [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(SCREEN_WIDETH-120);
            make.height.mas_equalTo(40);
            make.top.equalTo(self.view).offset(TopHeight-10);
        }];
    }
   
    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(SQ_resignFirstResponder)];
   
    NSOperationQueue*  mainQueue = [NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf.mapView addGestureRecognizer:tap];
    }];
    [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf.mapView removeGestureRecognizer:tap];
    }];
    
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREEN_WIDETH-60);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-30);
        make.height.mas_equalTo(48);
    }];
    
    [self.view addSubview:self.dingwei];
    [self.dingwei mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-100);
           make.size.mas_equalTo(50);
            make.right.equalTo(self.view.mas_right).offset(-10);
    }];
    [self.dingwei setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_setMap];
    }];
}
-(void)SQ_setMap{
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake([UserModel share].lat, [UserModel share].lng);
       // 设置地图显示区域的缩放级别
       float zoomLevel = 0.002;
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}


//位置已经改变了
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    self.addButton.btn.enabled = YES;
    CLLocationCoordinate2D  location =  [self.mapView convertPoint:CGPointMake(SCREEN_WIDETH/2.f, SCREEN_HEIGHT/2.f) toCoordinateFromView:self.mapView];
         CLGeocoder *gecoder = [[CLGeocoder alloc]init];
         CLLocation *locations = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    WS(weakSelf);
        [gecoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            if (placemarks.count > 0) {
                CLPlacemark * place = placemarks.firstObject;
               
                if ([place.thoroughfare isNotEmpty]) {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@",place.subLocality,place.thoroughfare];
                } else {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@",place.subLocality,place.name];
                }
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"null" withString:@""];
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"()" withString:@""];
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"nil" withString:@""];
            }
        }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField resignFirstResponder];
    if ([textField.text isNotEmpty]) {
        CLGeocoder *gecoder = [[CLGeocoder alloc]init];
        WS(weakSelf);
        [gecoder geocodeAddressString:textField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            DTLog(@"---%@",error);
            if (error!=nil) {
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请输入较为详细地址!")];
                return ;
            }
            if (placemarks.count==0) {
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"搜索结果为空!")];
                return ;
             }
            [weakSelf SQ_showAddressView:placemarks];
        }];
    }
    return  YES;
}
-(void)SQ_resignFirstResponder{
    [self.textField resignFirstResponder];
}

-(void)SQ_showAddressView:(NSArray<CLPlacemark *> *)placemarks{
    AddressBottomView * vc = [[AddressBottomView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 560)];
    [vc SQ_relodeView:placemarks];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc parentView:self.view popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [vc setAddressBlock:^(CLPlacemark * _Nonnull model) {
        [wk_pop dismiss];
        [weakSelf SQ_mapForAddress:model];
    }];
}
-(void)SQ_mapForAddress:(CLPlacemark*)model{
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake(model.location.coordinate.latitude, model.location.coordinate.longitude);
       // 设置地图显示区域的缩放级别
       float zoomLevel = 0.001;
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}

-(void)SQ_addAnntionForMap{
    if (![self.addressLabel.text isNotEmpty]) {
        [self SQ_headerButtonClick];
        return;
    }
    if (self.isEdit) {
        [YJProgressHUD SQ_showMsgWithoutView:@""];
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
         [dic setObject:self.addressLabel.text forKey:@"address"];
        
        [HttpTool post:Url5 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
            [self SQ_popViewVC];
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            [YJProgressHUD showMsgWithoutView:httpModel.message];
        }];
    } else {
        if (self.addressBlock) {
            self.addressBlock(self.addressLabel.text);
        }
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)SQ_headerButtonClick{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"定位权限设置") message:@"未检测到授权定位权限,请前往设置进行授权" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"去授权") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];

            if ([[UIApplication sharedApplication] canOpenURL:url]) {
               [[UIApplication sharedApplication] openURL:url];

            }
    }];
 
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co2];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)dealloc {
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode  = MKUserTrackingModeNone;
    [_mapView.layer removeAllAnimations];
    [_mapView removeAnnotations:_mapView.annotations];
    [_mapView removeOverlays:_mapView.overlays];
    [_mapView removeFromSuperview];
    _mapView.delegate = nil;
    _mapView = nil;
}
 
/** 懒加载地图视图 */
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
        /** 设置地图类型 */
        _mapView.mapType = MKMapTypeMutedStandard;
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        //设置地图可缩放
        _mapView.zoomEnabled = YES;
        //设置地图可滚动
        _mapView.scrollEnabled = YES;
        //设置地图可旋转
        _mapView.rotateEnabled = YES;
        //设置显示用户显示位置
        _mapView.showsUserLocation = YES;
        //为MKMapView设置delegate
        _mapView.delegate = self;
        _mapView.showsBuildings = YES;
        _mapView.showsTraffic = YES;
    }
    return _mapView;
}
 
- (UILabel *)addressLabel{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
//        _addressLabel.backgroundColor = SQHexColor(@"#000000", 0.3);
        _addressLabel.font = FONT_REGULAR(12);
        _addressLabel.textColor = UIColor.whiteColor;
        _addressLabel.numberOfLines = 0;
        _addressLabel.textAlignment = NSTextAlignmentCenter;
//        _addressLabel.layer.cornerRadius = 2;
    }
    return _addressLabel;
}

- (UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc]init];
        _textField.backgroundColor = SQHexColor(@"#FFFFFF", 0.4);
        _textField.placeholder = SQNSLocalString(@"输入你想查找的地址关键词");
        _textField.textColor = UIColor.whiteColor;
        _textField.layer.cornerRadius = 20;
        _textField.layer.borderColor = UIColor.whiteColor.CGColor;
        _textField.layer.borderWidth = 1;
        _textField.font = FONT_REGULAR(14);
        _textField.delegate = self;
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.layer.masksToBounds = YES;
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 36)];
        UIImageView * lefe = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 16, 16)];
        lefe.image = SQGetImage(@"输入");
        lefe.contentMode = UIViewContentModeScaleAspectFit;
        [bgView addSubview:lefe];
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.leftView = bgView;
     }
    return _textField;
}
- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.image = @"矩形";
        _addButton.colorString = @"#FFFFFF";
        [_addButton.btn addTarget:self action:@selector(SQ_addAnntionForMap) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.cornerRadius = 6;
        _addButton.layer.masksToBounds = YES;
        _addButton.text = SQNSLocalString(@"确认");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}
- (SQCustomButton *)dingwei{
    if (!_dingwei) {
        _dingwei = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
        _dingwei.image = SQGetImage(@"zishendingwei");
    }
    return _dingwei;
}

@end
